package com.fhnew.app.ui.dialogactivity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.icu.text.IDNA;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.util.Base64;
import android.view.View;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.fhnew.app.R;
import com.fhnew.app.global.Constants;
import com.fhnew.app.model.CustomObserver;
import com.fhnew.app.model.internet.been.B_Login;
import com.fhnew.app.model.internet.model.UserModel;
import com.fhnew.app.model.network.HttpJsonUtils;
import com.fhnew.app.model.network.entity.req.ResCode;
import com.fhnew.app.model.network.entity.req.Resberifystatus;
import com.fhnew.app.model.network.entity.req.Resmsg;
import com.fhnew.app.model.network.entity.req.Restyelogin;
import com.fhnew.app.ui.activity.userinfo.ActivityData;
import com.fhnew.app.ui.dialog.CheckOutDialog;
import com.fhnew.app.util.CheckView;
import com.fhnew.app.util.HLog;
import com.fhnew.app.util.Md5;
import com.fhnew.app.util.UrlUtils;
import com.fhnew.app.widget.CheckOutView;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;


/**
 * Created by Administrator on 2019/8/20.
 */

public class LoginDiolog extends FragmentActivity {

    private ImageView close;
    private EditText etusername;
    private EditText etpassword;
    private EditText etuserphone;
    private EditText phonecode;
    private TextView titletext;
    private TextView forgetpassbt;
    private TextView rigist2;
    private TextView code_bt;
    private CheckBox checkbox;
    private TextView passis;
    private TextView gologin;
    private TextView codeEt;
    private TextView codelogin;
    private TextView ponelogin;
    private TextView phonelogin;
    private TextView phoneforgetpassbt;
    private ImageView code_img;
    private View codeloginlin;
    private View phoneloginlin;
    private LinearLayout codeloginlayout;
    private LinearLayout phoneloginlayout;
    private LinearLayout VerificationLinea;

    private String username;
    private String password;
    CheckOutDialog dialog = new CheckOutDialog();
    public boolean TAG = false; //默认为滑块模式否为数字验证模式
    private String numberpassport;

    private void initView() {

        Constants.backgroundvoic = false;
        setContentView(R.layout.login_diolog);


        close = findViewById(R.id.close);
        code_img = findViewById(R.id.code_img);
        rigist2 = findViewById(R.id.rigist2);
        codeEt = findViewById(R.id.rigistidcode);
        titletext = findViewById(R.id.titletext);
        etusername = findViewById(R.id.etusername);
        etpassword = findViewById(R.id.etpassword);
        forgetpassbt = findViewById(R.id.forgetpassbt);
        checkbox = findViewById(R.id.checkbox);
        passis = findViewById(R.id.passis);
        gologin = findViewById(R.id.gologin);
        codelogin = findViewById(R.id.codelogin);
        ponelogin = findViewById(R.id.ponelogin);
        codeloginlin = findViewById(R.id.codeloginlin);
        phoneloginlin = findViewById(R.id.phoneloginlin);
        codeloginlayout = findViewById(R.id.codeloginlayout);
        phoneloginlayout = findViewById(R.id.phoneloginlayout);
        etuserphone = findViewById(R.id.etuserphone);
        phoneforgetpassbt = findViewById(R.id.phoneforgetpassbt);
        phonelogin = findViewById(R.id.phonelogin);
        code_bt = findViewById(R.id.code_bt);
        phonecode = findViewById(R.id.phonecode);
        VerificationLinea = findViewById(R.id.VerificationLinea);


        phonelogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (UrlUtils.isFastClick()) {
                    if (!TextUtils.isEmpty(etuserphone.getText().toString().trim()) && !TextUtils.isEmpty(phonecode.getText().toString().trim())) {
                        phonelogin(etuserphone.getText().toString().trim(), phonecode.getText().toString().trim());
                    } else {
                        Toast.makeText(LoginDiolog.this, "请输入正确信息", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });


        code_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(etuserphone.getText().toString().trim())) {
                    sendmsg(etuserphone.getText().toString().trim());
                } else {
                    Toast.makeText(LoginDiolog.this, "请输入手机号", Toast.LENGTH_SHORT).show();
                }
            }
        });


        phoneforgetpassbt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (UrlUtils.isFastClick()) {
                    startActivity(new Intent(LoginDiolog.this, ForgetActivity.class));
                }
            }
        });
        forgetpassbt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (UrlUtils.isFastClick()) {
                    startActivity(new Intent(LoginDiolog.this, ForgetActivity.class));
                }
            }
        });

        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        codelogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                codelogin.setTextColor(getResources().getColor(R.color.moccasin));
                ponelogin.setTextColor(getResources().getColor(R.color.settingbg));
                codeloginlin.setBackgroundResource(R.color.moccasin);
                phoneloginlin.setBackgroundResource(R.color.settingbg);
                codeloginlin.setVisibility(View.VISIBLE);
                phoneloginlin.setVisibility(View.INVISIBLE);
                codeloginlayout.setVisibility(View.VISIBLE);
                phoneloginlayout.setVisibility(View.GONE);
            }
        });
        ponelogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ponelogin.setTextColor(getResources().getColor(R.color.moccasin));
                codelogin.setTextColor(getResources().getColor(R.color.settingbg));
                phoneloginlin.setBackgroundResource(R.color.moccasin);
                codeloginlin.setBackgroundResource(R.color.settingbg);
                phoneloginlin.setVisibility(View.VISIBLE);
                codeloginlin.setVisibility(View.INVISIBLE);
                phoneloginlayout.setVisibility(View.VISIBLE);
                codeloginlayout.setVisibility(View.GONE);
            }
        });

        code_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getberifystatus();
            }
        });

        rigist2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (UrlUtils.isFastClick()) {
                    finish();
                    startActivity(new Intent(LoginDiolog.this, RegisterActivity.class));
                }
            }
        });

        gologin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (UrlUtils.isFastClick()) {
                    password = Md5.toMd5(etpassword.getText().toString().trim());
                    username = etusername.getText().toString().trim();
                    userModel.setUserLoginStatus(username, etpassword.getText().toString().trim(), checkbox.isChecked());

                    if (!TextUtils.isEmpty(password) && !TextUtils.isEmpty(username)) {
                        if (TAG) {
                            login(username, password, codeEt.getText().toString().trim(), numberpassport + "");
                        } else {
                            getSlideVerify();
                        }
                    } else {
                        Toast.makeText(LoginDiolog.this, "您未输入用户名或密码", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });

    }

    private void getSlideVerify() {
        HttpJsonUtils.getHttpApiInstance()
                .tyelogin(Constants.getuseAdress() + "api/m/SlideVerify")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new CustomObserver<Restyelogin>() {
                    @Override
                    protected void onCustomNext(Restyelogin restyelogin) {

                        int index = restyelogin.bg_pic.url.indexOf(",");
                        String bg_picurl = restyelogin.bg_pic.url.substring(index + 1);

                        int index1 = restyelogin.ico_pic.url.indexOf(",");
                        String ico_picurl = restyelogin.ico_pic.url.substring(index1 + 1);
                        dialog.init(bg_picurl,
                                restyelogin.bg_pic.w,
                                restyelogin.bg_pic.h,
                                ico_picurl,
                                restyelogin.ico_pic.w,
                                restyelogin.ico_pic.h,
                                restyelogin.y_point
                        );
                        dialog.setCheckOutListener(new CheckOutView.CheckOutListener() {
                            @Override
                            public void seekEnd(float value) {
                                HLog.I("滑动位置" + value);
                                login(username, password, value + "", restyelogin.passport + "");
                            }
                        });
                        dialog.show(getSupportFragmentManager(), "1");
                    }

                    @Override
                    protected void onSubscribeCustom(Disposable disposable) {
                    }

                    @Override
                    protected void onErrorCustom(Throwable e) {

                    }
                });

    }

    private void initConstantsView() {
        if (userModel.getSavePassword()) {
            checkbox.setChecked(true);
            etusername.setText(userModel.getUserName());
            etpassword.setText(userModel.getUserPassword());
        } else {
            checkbox.setChecked(false);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);
        initView();
        //获取验证码验证类型
        getberifystatus();
        initInfo();
    }

    /**
     * 验证类型，0数字   1图形验证
     */
    private void getberifystatus() {
        HttpJsonUtils.getHttpApiInstance()
                .getberifystatus(Constants.getuseAdress() + "api/m/lottery/getSourceData")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new CustomObserver<Resberifystatus>() {
                    @Override
                    protected void onCustomNext(Resberifystatus resberifystatus) {
                        if (resberifystatus.code == 0) {
                            //默认为0滑块模式，1为数字验证模式
                            if ("0".equals(resberifystatus.data.LoginVerType)) {
                                //隐藏
                                VerificationLinea.setVisibility(View.GONE);
                                TAG = false;
                            } else {
                                //放出来
                                VerificationLinea.setVisibility(View.VISIBLE);
                                TAG = true;
                                getCode();
                            }
                        }
                    }

                    @Override
                    protected void onSubscribeCustom(Disposable disposable) {
                    }

                    @Override
                    protected void onErrorCustom(Throwable e) {

                    }
                });
    }

    /**
     * 获取动态验证码
     */
    private void getCode() {
        HttpJsonUtils.getHttpApiInstance()
                .getcode(Constants.getuseAdress() + "api/m/captcha")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new CustomObserver<ResCode>() {
                    @Override
                    protected void onSubscribeCustom(Disposable disposable) {

                    }

                    @Override
                    protected void onErrorCustom(Throwable e) {

                    }

                    @Override
                    protected void onCustomNext(ResCode resCode) {
                        if (null != resCode.data){
                            numberpassport = "";
                            numberpassport = resCode.data.captcha_code;
                            Bitmap bitmap = null;
                            byte[] bitmapArray;
                            bitmapArray = Base64.decode(resCode.data.code, Base64.NO_WRAP);
                            bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
                            code_img.setImageBitmap(bitmap);//显示图片
                        }

                    }
                });
    }

    @Override
    protected void onResume() {
        super.onResume();
        initConstantsView();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        timer.cancel();
    }


    //===========================================================================================
    // Model
    //===========================================================================================

    private UserModel userModel;

    public void initInfo() {
        userModel = UserModel.getInstance(this);
    }

    //===========================================================================================
    //网络请求
    //===========================================================================================

    private void phonelogin(String trim, String s) {
        HttpJsonUtils.getHttpApiInstance()
                .mobileLogin(Constants.getuseAdress() + "api/m/mobileLogin", trim, s, "")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new CustomObserver<B_Login>() {
                    @Override
                    protected void onCustomNext(B_Login resLogin) {
                        if (resLogin.getCode() == 0 && resLogin.getData() != null) {
                            userModel.login(resLogin.getData());
                            Toast.makeText(LoginDiolog.this, "登录成功", Toast.LENGTH_SHORT).show();
                            finish();
                        } else {
                            Toast.makeText(LoginDiolog.this, "" + resLogin.getMsg(), Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    protected void onSubscribeCustom(Disposable disposable) {
                    }

                    @Override
                    protected void onErrorCustom(Throwable e) {

                    }
                });
    }

    private void login(String username, String password, String value, String passport) {
//        HLog.I("用户名" + username + "密码" + password);
        HttpJsonUtils.getHttpApiInstance()
                .login(Constants.getuseAdress() + "api/m/login", username, password, value, passport, UserModel.Token)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new CustomObserver<B_Login>() {
                    @Override
                    protected void onCustomNext(B_Login resLogin) {
                        if (resLogin.getCode() == 0 && resLogin.getData() != null) {
                            userModel.login(resLogin.getData());
                            if (resLogin.getData().forcePasswordChange.equals("1")) {
                                Toast.makeText(LoginDiolog.this, "您的密码不符合规定，请尽快修改", Toast.LENGTH_LONG).show();
                                Intent intent = new Intent(LoginDiolog.this, ActivityData.class);
                                intent.putExtra("intentm", "密码");
                                startActivity(intent);
//                                EventBus.getDefault().post(new ReloginEvent("200"));
                            } else {
                                Toast.makeText(LoginDiolog.this, "登录成功", Toast.LENGTH_SHORT).show();
                            }
                            finish();

                        } else {
                            Toast.makeText(LoginDiolog.this, "" + resLogin.getMsg(), Toast.LENGTH_LONG).show();
                            dialog.dismiss();
                        }
                    }

                    @Override
                    protected void onSubscribeCustom(Disposable disposable) {
                    }

                    @Override
                    protected void onErrorCustom(Throwable e) {

                    }
                });
    }

    private void sendmsg(String trim) {
        HttpJsonUtils.getHttpApiInstance()
                .sendmsg(Constants.getuseAdress() + "api/m/smsCode/" + trim, "1", "login")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new CustomObserver<Resmsg>() {
                    @Override
                    protected void onCustomNext(Resmsg resLogin) {
                        if (resLogin.status) {
                            //成功
                            timer.start();
                            Toast.makeText(LoginDiolog.this, resLogin.msg, Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(LoginDiolog.this, resLogin.msg, Toast.LENGTH_SHORT).show();
                            timer.cancel();
                        }
                    }

                    @Override
                    protected void onSubscribeCustom(Disposable disposable) {
                    }

                    @Override
                    protected void onErrorCustom(Throwable e) {

                    }
                });
    }


    //=======================================================================================
    // 工具
    //=======================================================================================

    CountDownTimer timer = new CountDownTimer(60000, 1000) {

        @Override
        public void onTick(long millisUntilFinished) {
            code_bt.setText((millisUntilFinished / 1000) + "S后重发");
            code_bt.setEnabled(false);
        }

        @Override
        public void onFinish() {
            code_bt.setEnabled(true);
            code_bt.setText("获取验证码");
        }
    };

}
